module EasyForm
  module ActionViews
    module FormHelper
      def easy_form_for(record, options = {}, &block)
        options[:builder] ||= EasyForm::FormBuilder
        without_default_field_error do
          form_for record, options, &block
        end
      end

      def easy_fields_for(record_name, record_obj = nil, options = {}, &block)
        options, record_obj = record_obj, nil if record_obj.is_a?(Hash) && record_obj.extractable_options?
        options[:builder] ||= EasyForm::FormBuilder
        without_default_field_error do
          fields_for record_name, record_obj, options, &block
        end
      end

      private
      #把默认的验证错误提示去掉，之后要重新加回来
      def without_default_field_error
        original = ::ActionView::Base.field_error_proc
        begin
          ::ActionView::Base.field_error_proc = EasyForm.field_error_proc
          yield
        ensure
          ::ActionView::Base.field_error_proc = original
        end

      end

    end
  end
end

ActiveSupport.on_load :action_view do
  #self is ActionView::Base
  self.include EasyForm::ActionViews::FormHelper
end

module ActionView::Helpers
  class FormBuilder
    def easy_fields_for(*args, &block)
      options = args.extract_options!
      options[:wrapper] = self.options[:wrapper] if options[:wrapper].nil?
      options[:defaults] ||= self.options[:wrapper_mappings]

      # < 用来判断继承关系
      if self.class < ActionView::Helpers::FormBuilder
        options[:builder] ||= self.class
      else
        options[:builder] ||= EasyForm::FormBuilder
      end

      fields_for *args, options, &block
    end
  end
end
